<template>
  <div class="page-Body">
    <h2 class="page-title">用户管理</h2>
    <!-- 表单 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="用户名称">
        <el-input
          v-model="formInline.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 150px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input
          v-model="formInline.mobile"
          type="number"
          placeholder="请输入手机号码"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item label="用户状态">
        <el-select
          v-model="formInline.banned"
          placeholder="请输入用户状态"
          clearable
          style="width: 150px"
        >
          <el-option label="启用" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <TimeFormatter
          @TimeChild="TimeHandle"
          ref="childComponentRef"
        ></TimeFormatter>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="Search">搜索</el-button>
        <el-button @click="Reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 新增对话框组件 -->
    <el-button plain @click="AddOpenDialog" class="el-DiaButton" type="primary">
      添加
    </el-button>
    <AddUser_Dialog
      @confirm="AddConfirm"
      @cancel="AddClose"
      :dialogAdd="dialogAdd"
    />
    <!-- 表格 -->
    <el-table
      ref="myTableRef"
      :data="tableData"
      border
      stripe
      fit
      empty-text="暂无数据"
      show-header
      v-loading="loading"
      size="default"
      element-loading-text="Loading..."
      :header-cell-style="{ background: '#e7e1fb' }"
      style="width: 100%"
      max-height="540px"
    >
      <el-table-column prop="uid" label="序号" />
      <el-table-column prop="userName" label="用户名称" />
      <el-table-column prop="mobile" label="手机号" />
      <el-table-column prop="createTime" label="添加时间" />
      <el-table-column prop="banned" label="状态" v-slot="scope">
        <span :style="scope.row.banned === 0 ? {} : { color: 'red' }">
          {{ scope.row.banned === 0 ? '启用' : '禁用' }}
        </span>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" v-slot="scope">
        <el-button
          link
          type="primary"
          @click="ModifyOpenDialog(scope.row.uid, scope.row.password)"
        >
          修改
        </el-button>
        <el-button
          link
          type="primary"
          @click="RevisePassWord(scope.row.roleCode, scope.row.uid)"
        >
          {{ scope.row.roleCode === 'admin' ? '重置密码' : '修改密码' }}
        </el-button>
        <el-button link type="danger" @click="Del(scope.row.uid)">
          删除
        </el-button>
      </el-table-column>
    </el-table>
    <!-- 修改对话框组件 -->
    <ModifyUserDialog
      @confirm="ModifyConfirm"
      @cancel="ModifyClose"
      :dialogModify="dialogModify"
      :uid="uid"
      :NewModifyList="NewModifyList"
      :Modifypassword="passwords"
    />
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="dialogpassword"
      :title="passwordtitle"
      width="400"
      :before-close="handleClose"
    >
      <el-form
        :model="formPassword"
        label-position="left"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item
          label="原密码"
          prop="password"
          label-width="100px"
          v-if="passwordtitle !== '重置密码'"
        >
          <el-input
            type="password"
            v-model="formPassword.password"
            style="width: 240px"
            v-noSpace
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" label-width="100px">
          <el-input
            type="password"
            v-model="formPassword.newPassword"
            style="width: 240px"
            v-noSpace
          />
        </el-form-item>
        <el-form-item
          label="确认新密码"
          prop="CancelnewPassword"
          label-width="100px"
        >
          <el-input
            type="password"
            v-model="formPassword.CancelnewPassword"
            style="width: 240px"
            :disabled="!formPassword.newPassword"
            v-noSpace
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogpassword = false">取消</el-button>
          <el-button type="primary" @click="Cancelpassword">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分页器 -->
    <div class="pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 40, 80, 100]"
        background
        layout="total,sizes, prev, pager, next,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { getUserList, DelList, ModifyPwd } from '@/api/permission/user';
import { ref, onMounted } from 'vue';
import AddUser_Dialog from '@/components/permission/AddUser_Dialog.vue';
import ModifyUserDialog from '@/components/permission/ModifyUserDialog.vue';
import TimeFormatter from '@/components/permission/TimeFormatter.vue';
// 分页变量
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
// 修改重置密码
const formPassword = ref({
  password: '',
  newPassword: '',
  CancelnewPassword: '',
});
// 对话框
const dialogAdd = ref(false);
const dialogModify = ref(false);
const dialogpassword = ref(false);
const uid = ref('');
const passwordUid = ref(0);
const NewModifyList = ref([]);
const passwords = ref('');
const passwordtitle = ref('');
// 表单-时间选择器
const childComponentRef = ref(null);
const TimeArray = ref([]);
// 表单数据
const formInline = ref({
  userName: '',
  mobile: '',
  banned: '',
});
// 列表数据+表单校验
const tableData = ref([]);
const loading = ref(true);
const myTableRef = ref(null);
// 校验规则
const formRef = ref(null);
const rules = {
  password: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  CancelnewPassword: [
    { required: true, message: '请确认新密码' },
    // 自定义验证函数
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请确认新密码'));
        } else if (value !== formPassword.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
};
// 分页逻辑
const handleSizeChange = async (val) => {
  pageSize.value = val;
  UserList();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  UserList();
};
// 获取列表
const UserList = async () => {
  loading.value = true;
  const res = await getUserList({
    current: currentPage.value,
    size: pageSize.value,
    query: {},
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data.items;
    total.value = res.data.data.counts || 0;
    loading.value = false;
  }
};
// 重置修改密码
const RevisePassWord = (roleCode, uid) => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  formPassword.value = {};
  passwordUid.value = uid;
  dialogpassword.value = true;
  passwordtitle.value = roleCode === 'admin' ? '重置密码' : '修改密码';
};
const handleClose = () => {
  dialogpassword.value = false;
};
const Cancelpassword = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await ModifyPwd({
        uid: passwordUid.value,
        password: formPassword.value.password,
        newPassword: formPassword.value.newPassword,
      });
      if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'success',
        });
        handleClose();
        UserList();
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'error',
        });
      }
    }
  });
};
// 检查搜索条件是否为空
const hasSearchConditions = () => {
  const { userName, mobile, banned } = formInline.value;
  const hasTimeRange = TimeArray.value && TimeArray.value.length === 2;

  return userName || mobile || banned || hasTimeRange;
};
// 搜索
const Search = async () => {
  if (!hasSearchConditions()) {
    // eslint-disable-next-line no-undef
    ElMessage({
      message: '请至少输入一个搜索条件',
      type: 'warning',
    });
    return;
  }

  loading.value = true;
  const res = await getUserList({
    current: currentPage.value,
    size: pageSize.value,
    query: { ...formInline.value },
    startDate: TimeArray.value[0],
    endDate: TimeArray.value[1],
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data.items;
    total.value = res.data.data.counts || 0;
    loading.value = false;
  }
};
// 重置
const Reset = () => {
  // 如果当前已经是空值状态，直接返回
  if (
    formInline.value.userName === '' &&
    formInline.value.mobile === '' &&
    formInline.value.banned === '' &&
    TimeArray.value.length === 0
  ) {
    return;
  }
  formInline.value = {
    userName: '',
    mobile: '',
    banned: '',
  };
  if (childComponentRef.value) {
    childComponentRef.value.clear();
  }
  TimeArray.value = [];
  currentPage.value = 1;
  UserList();
};

// 删除
const Del = async (id) => {
  // eslint-disable-next-line no-undef
  ElMessageBox.confirm('确定删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await DelList(id);
      if (res.data.code === 3000) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '无权限操作',
          type: 'warning',
        });
      } else if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '删除成功',
          type: 'success',
        });
        UserList();
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'warning',
        });
      }
    })
    .catch(() => {});
};
// 添加功能对话框
const AddOpenDialog = () => {
  dialogAdd.value = true;
};

const AddConfirm = () => {
  dialogAdd.value = false;
  UserList();
};
const AddClose = () => {
  dialogAdd.value = false;
};

// -------------------------------------------------
// 修改功能对话框

const ModifyOpenDialog = (id, password) => {
  NewModifyList.value = tableData.value.filter((item) => {
    return item.uid == id;
  });
  uid.value = id;
  // 传入密码
  passwords.value = password;

  dialogModify.value = true;
};

const ModifyConfirm = () => {
  dialogModify.value = false;
  UserList();
};
const ModifyClose = () => {
  dialogModify.value = false;
};
//获取时间
const TimeHandle = (data) => {
  TimeArray.value = data;
};
onMounted(() => {
  UserList();
});
</script>

<style lang="scss" scoped>
.el-DiaButton {
  width: 120px;
  height: 40px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #c7d4ff;
}
</style>
